package com.niiwoo.civet.trade.service.dubbo.org;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.config.annotation.Service;
import com.niiwoo.asset.org.business.dto.request.*;
import com.niiwoo.asset.org.business.dto.response.*;
import com.niiwoo.asset.org.business.service.dubbo.OrderContactDubboService;
import com.niiwoo.asset.org.business.service.dubbo.OrgProjectOrderDubboService;
import com.niiwoo.civet.trade.dao.entity.Project;
import com.niiwoo.civet.trade.dao.mapper.ProjectMapperExt;
import com.niiwoo.civet.trade.dto.common.ProjectDTO;
import com.niiwoo.civet.trade.dto.request.myloan.LoanVoucherAuditInfoQueryRequestDTO;
import com.niiwoo.civet.trade.dto.response.LendOrderResponseDTO;
import com.niiwoo.civet.trade.dto.response.myloan.LoanVoucherAuditInfoQueryResponseDTO;
import com.niiwoo.civet.trade.dto.response.org.AssetOrgProjectResponseDTO;
import com.niiwoo.civet.trade.dto.response.org.ProjectBorrowerPlanNewResponseDTO;
import com.niiwoo.civet.trade.dto.response.orgloan.*;
import com.niiwoo.civet.trade.service.local.org.OrgProjectLocalService;
import com.niiwoo.civet.trade.service.org.OrgProjectDubboService;
import com.niiwoo.civet.trade.service.project.ProjectDubboService;
import com.niiwoo.civet.user.dto.response.OrgInfoRespDTO;
import com.niiwoo.civet.user.service.OrganizationDubboService;
import com.niiwoo.tripod.provider.exception.BizException;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

@Service(version="1.0.0")
public class OrgProjectDubboServiceImpl implements OrgProjectDubboService {
	
	@Autowired
	private OrgProjectLocalService orgProjectLocalService;
	@Autowired
	private ProjectMapperExt projectMapperExt;


	@Reference(version = "1.0.0")
	private OrganizationDubboService organizationDubboService;
    @Reference(version = "1.0.0")
	private OrgProjectOrderDubboService orgProjectOrderDubboService;
    @Reference(version = "1.0.0")
    private ProjectDubboService projectDubboService;
	@Reference(version = "1.0.0")
	private OrderContactDubboService orderContactDubboService;

	@Override
	public AssetOrgProjectResponseDTO getAsserOrgProject(String orgId,Long orderId) {
		return orgProjectLocalService.getAsserOrgProject(orgId,orderId);
	}

	@Override
	public AssetOrgProjectResponseDTO getAsserOrgProject(Long projectId) {
		return orgProjectLocalService.getAsserOrgProject(projectId);
	}

	@Override
	public void syncProjectStatus(Long projectId) {
		orgProjectLocalService.syncProjectStatus(projectId);
	}

	@Override
	public void syncProjectStatusByJob() {
		orgProjectLocalService.syncProjectStatusByJob();
	}

	@Override
	public List<ProjectBorrowerPlanNewResponseDTO> getProjectBorrowerPlanNew(Long projectId) {
		return orgProjectLocalService.getProjectBorrowerPlanNew(projectId);
	}

	@Override
	public LendOrderResponseDTO getLendOrder(Long projectId) {
		return orgProjectLocalService.getLendOrder(projectId);
	}

	@Override
	public String getProjectContractViewUrl(Long projectId) {
		return orgProjectLocalService.getProjectContractViewUrl(projectId);
	}
    //查询借款企业信息
	@Override
	public OrgInfoResponseDTO queryLoanOrgInfo(Long projectId) {
		OrgInfoResponseDTO responseDTO = new OrgInfoResponseDTO();
		OrgInfoRespDTO orgInfoRespDTO =new OrgInfoRespDTO();
		AssetOrgProjectResponseDTO project =orgProjectLocalService.getAsserOrgProject(projectId);
		if (project == null){
			throw new BizException("MWT50001","标的不存在");
		}
		ProjectDTO projectDTO = projectDubboService.selectProjectById(projectId);
		String orgId =String.valueOf(projectDTO.getBorrowUserId());
		orgInfoRespDTO= organizationDubboService.queryOrgInfoById(orgId);
		BeanUtils.copyProperties(orgInfoRespDTO,responseDTO);
		responseDTO.setOrgShortName(orgInfoRespDTO.getOrgShortName());
		responseDTO.setOrgName(orgInfoRespDTO.getOrgName());
		responseDTO.setOfficeAddress(this.maskPlace(orgInfoRespDTO.getCity()+orgInfoRespDTO.getAddress()));
		ApplyCompanyQueryReqDTO reqDTO = new ApplyCompanyQueryReqDTO();
		reqDTO.setOrderId(project.getOrderId());
		OrgApplyOrderCompanyRespDTO companyRespDTO = orgProjectOrderDubboService.queryApplyOrderCompany(reqDTO);
		responseDTO.setOperatingAge(companyRespDTO.getOperatingAge());
		responseDTO.setTelephoneNumber(this.maskCompanyPhone(companyRespDTO.getCompanyPhone()));
		responseDTO.setRegisterDate(companyRespDTO.getRegisterDate());
		responseDTO.setRepresentative(this.maskName(companyRespDTO.getLegalRepresentative()));

		//联系人信息
		OrderContractReqDTO contractReqDTO = new OrderContractReqDTO();
		contractReqDTO.setOrderId(project.getOrderId());
		List<OrderContractRespDTO> contractList = orderContactDubboService.queryContractList(contractReqDTO);
		if (contractList != null && !contractList.isEmpty()) {
			List<OrgApplyLinkManInfoDTO> list = new ArrayList<>();
			long k = 1;
			for(OrderContractRespDTO contract: contractList){
				OrgApplyLinkManInfoDTO linkManInfoDTO = new OrgApplyLinkManInfoDTO();
				linkManInfoDTO.setOrderNo(k);
				linkManInfoDTO.setMobileNo(contract.getContactMobile());
				linkManInfoDTO.setName(this.maskName(contract.getContactName()));
				linkManInfoDTO.setRelation(this.getLinkTypeByOrgType(contract.getContactRelation()));
				list.add(linkManInfoDTO);
				k++;
				if(list.size() >= 2){
					break;
				}
			}
			responseDTO.setLinkManInfoDTOList(list);
		}
		return responseDTO;
	}
	public String maskName(String Name) {
		//为空 或者是本人，则不需要打码
		if(!StringUtils.hasText(Name)){
			return Name;
		}
		return Name.substring(0, 1) + "**";
	}
	public String maskCompanyPhone(String companyPhone) {
		if(!StringUtils.hasText(companyPhone)){
			return companyPhone;
		}
		return companyPhone.substring(0,4)+"****";
	}
	public String maskPlace(String place){
		if(!StringUtils.hasText(place)){
			return place;
		}
		int cityIndex = place.indexOf("市");
		return place.substring(0,cityIndex+1)+"*****";
	}
	/**
	 * 查询机构信息
	 * @param projectId
	 * @return
	 */
	@Override
	public OrgInfoResponseDTO queryOrgInfo(Long projectId) {
		OrgInfoResponseDTO responseDTO = new OrgInfoResponseDTO();
		OrgInfoRespDTO orgInfoRespDTO =new OrgInfoRespDTO();
		AssetOrgProjectResponseDTO project =orgProjectLocalService.getAsserOrgProject(projectId);
		if (project == null){
			throw new BizException("MWT50001","标的不存在");
		}
		String orgId =String.valueOf(project.getOrgId());
		orgInfoRespDTO= organizationDubboService.queryOrgInfoById(orgId);
		BeanUtils.copyProperties(orgInfoRespDTO,responseDTO);


		return responseDTO;

	}

	//查询房产信息
	@Override
	public OrgApplyHouseResponseDTO queryOrgApplyHouse(Long projectId) {
		OrgApplyHouseResponseDTO responseDTO = new OrgApplyHouseResponseDTO();
		AssetOrgProjectResponseDTO project =orgProjectLocalService.getAsserOrgProject(projectId);
		if (project != null){
			ApplyHouseQueryReqDTO reqDTO = new ApplyHouseQueryReqDTO();
			reqDTO.setOrderId(project.getOrderId());
			OrgApplyHouseRespDTO respDTO = orgProjectOrderDubboService.queryApplyHouseInfo(reqDTO);
			if (respDTO != null){
				BeanUtils.copyProperties(respDTO,responseDTO);
			}
		}

		return responseDTO;
	}

	/**
	 * 查询借款个人标的信息
	 * @param projectId
	 * @return
	 */
	public OrgApplyLoanInfoResponseDTO queryOrgApplyLoanInfo(Long projectId){
		OrgApplyLoanInfoResponseDTO responseDTO = new OrgApplyLoanInfoResponseDTO();
		AssetOrgProjectResponseDTO project =orgProjectLocalService.getAsserOrgProject(projectId);
		if (project != null){
			ApplyHouseQueryReqDTO reqDTO = new ApplyHouseQueryReqDTO();
			reqDTO.setOrderId(project.getOrderId());
			OrgApplyHouseRespDTO respDTO = orgProjectOrderDubboService.queryApplyHouseInfo(reqDTO);
			Project projectInfo = projectMapperExt.selectByPrimaryKey(projectId);
			// 鸿特机构标借款人信息_基本信息中，若为“共借”借款，则不显示房产信息  (是否主借人?0.否;1.是)
			Boolean isShowHouse = projectInfo != null && projectInfo.getIsMasterBorrower() != null && projectInfo.getIsMasterBorrower().equals(Byte.valueOf("0"));
			if (respDTO != null && !isShowHouse){
				OrgApplyHouseResponseDTO houseResponseDTO = new OrgApplyHouseResponseDTO();
				BeanUtils.copyProperties(respDTO,houseResponseDTO);
				responseDTO.setOrgApplyHouseResponseDTO(houseResponseDTO);
			}
			//个人信息查询
			ApplyPersonQueryReqDTO reqPersonDTO = new ApplyPersonQueryReqDTO();
			reqPersonDTO.setOrderId(project.getOrderId());
			OrgApplyPersonRespDTO personRespDTO = orgProjectOrderDubboService.queryApplyPersonInfo(reqPersonDTO);
			if(personRespDTO != null){
				OrgApplyPersonResponseDTO personResponseDTO = new OrgApplyPersonResponseDTO();
				BeanUtils.copyProperties(personRespDTO,personResponseDTO);
				responseDTO.setOrgApplyPersonResponseDTO(personResponseDTO);
			}
			//工作信息查询
			ApplyWorkQueryReqDTO reqWorkDTO = new ApplyWorkQueryReqDTO();
			reqWorkDTO.setOrderId(project.getOrderId());
			OrgApplyWorkRespDTO workRespDTO = orgProjectOrderDubboService.queryApplyWorkInfo(reqWorkDTO);
			if (workRespDTO != null){
				OrgApplyWorkResponseDTO workResponseDTO = new OrgApplyWorkResponseDTO();
				BeanUtils.copyProperties(workRespDTO,workResponseDTO);
				responseDTO.setOrgApplyWorkResponseDTO(workResponseDTO);
			}
			//联系人信息
			OrderContractReqDTO contractReqDTO = new OrderContractReqDTO();
			contractReqDTO.setOrderId(project.getOrderId());
			List<OrderContractRespDTO> contractList = orderContactDubboService.queryContractList(contractReqDTO);
			if (contractList != null && !contractList.isEmpty()) {
				List<OrgApplyLinkManInfoDTO> list = new ArrayList<>();
				long k = 1;
				for(OrderContractRespDTO contract: contractList){
					OrgApplyLinkManInfoDTO linkManInfoDTO = new OrgApplyLinkManInfoDTO();
					linkManInfoDTO.setOrderNo(k);
					linkManInfoDTO.setRelation(this.getLinkTypeByOrgType(contract.getContactRelation()));
					linkManInfoDTO.setMobileNo(contract.getContactMobile());
					linkManInfoDTO.setName(contract.getContactName());
					list.add(linkManInfoDTO);
					k++;
					if(list.size() >= 2){
						break;
					}
				}
				responseDTO.getOrgApplyPersonResponseDTO().setLinkManInfoDTOList(list);
			}
		}
		return responseDTO;
	}

	/**
	 * 转换为统一的联系人类型（关系：1-配偶，2-父亲，3-母亲，4-兄弟，5-姐妹，6-子女，7-其他 , 8-同事 ，9-朋友）
	 * @param orgType
	 * @return
	 */
	private Byte getLinkTypeByOrgType(Byte orgType){
		Byte subType = new Byte("0");
		if (orgType == 0){
			subType = Byte.valueOf("2");
		}else if (orgType == 1){
			subType = Byte.valueOf("3");
		}else if (orgType == 2){
			subType = Byte.valueOf("4");
		}else if (orgType == 3){
			subType = Byte.valueOf("5");
		}else if (orgType == 4){
			subType = Byte.valueOf("6");
		}else if (orgType == 7){
			subType = Byte.valueOf("7");
		}else if (orgType == 8){
			subType = Byte.valueOf("1");
		}else if (orgType == 5){
			subType = Byte.valueOf("8");
		}else if (orgType == 6){
			subType = Byte.valueOf("9");
		}
		return subType;
	}

	/**
	 * 借款凭证查询
	 * @param projectId
	 * @param loginUserId
	 * @param borrowUserId
	 * @return
	 */
	@Override
	public LoanVoucherAuditInfoQueryResponseDTO loanVoucherAuditInfoQuery(Long projectId, String loginUserId, String borrowUserId) {
		LoanVoucherAuditInfoQueryRequestDTO requestDTO = new LoanVoucherAuditInfoQueryRequestDTO();
		requestDTO.setBorrowUserId(borrowUserId);
		requestDTO.setLoginUserId(loginUserId);
		requestDTO.setProjectId(projectId);
		LoanVoucherAuditInfoQueryResponseDTO responseDTO = orgProjectLocalService.loanVoucherAuditInfoQuery(requestDTO);
		if (responseDTO == null){
			return null;
		}

		return responseDTO;
	}


	@Override
	public void updateFundraisingEndTime(String orgId, Long orderId) {
		orgProjectLocalService.updateFundraisingEndTime(orgId, orderId);
	}
}
